<script setup lang="ts">
import type { Project } from '#/api/business/services/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { projectAdd, projectUpdate } from '#/api/business/services';
import { uploadApiNew } from '#/api/core/upload';
import { formatToFen, formatToYuan } from '#/utils/common';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const projectImg = ref<string>('');
const handleUpload = (file: File) => {
  uploadApiNew({
    file,
    onSuccess: (data) => {
      projectImg.value = data.objectName;
    },
  });
};
const handleRemove = () => {
  projectImg.value = '';
};
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(handleUpload, handleRemove),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const {
      id,
      projectImg: projectImgValue,
      projectPrice,
      ...rest
    } = cloneDeep(modalApi.getData()) as Project;
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const objectName = projectImgValue.split('/').pop();
      projectImg.value = objectName || '';
      await formApi.setValues({
        ...rest,
        id,
        projectImg: projectImgValue
          ? [
              {
                uid: '-1',
                name: objectName,
                status: 'done',
                url: projectImgValue,
              },
            ]
          : undefined,
        projectPrice: projectPrice ? formatToYuan(projectPrice) : undefined,
      });
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    const data = cloneDeep(await formApi.getValues());

    data.projectImg = projectImg.value;
    data.projectPrice = formatToFen(data.projectPrice);
    await (isUpdate.value ? projectUpdate(data) : projectAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm />
  </BasicModal>
</template>
